#!/bin/sh
echo "lmdprogress:2"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"

echo "lmdprogress:3"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_conda.sh"

echo "lmdprogress:5"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_node.sh"
echo "lmdprogress:15"
APP_INSTALL_NAME="n8n"
export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_INSTALL_NAME}"
echo $CURRENT_APP_PATH
mkdir -p "$CURRENT_APP_PATH"

if [ -d "$CURRENT_APP_PATH" ]; then
  echo "App Dir: "$CURRENT_APP_PATH
else
  echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
  exit 1
fi

source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/${APP_INSTALL_NAME}/env"
export GIT_HOST=${GITHUB_PROXY}"https://github.com"

echo "lmdprogress:18"

if [ -n "$GITHUB_PROXY" ]; then
  # if GITHUB_PROXY value exist, use npm mirror.
  NPM_MIRROR_PARAM="--registry=https://registry.npmmirror.com"
  echo "use npm mirror "$NPM_MIRROR_PARAM
fi
npm -v
node -v

echo "lmdprogress:20"

cp "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/package.json" "$CURRENT_APP_PATH"

echo "lmdprogress:50"

NPM_CACHE_PARAM="--cache ${LMD_DATA_ROOT}/install-cache/npm"

export NODE_OPTIONS=--max-old-space-size=4096


cd "${CURRENT_APP_PATH}"

# install_node_modules() {
#   echo "install cnpm"
#   npm install cnpm --save-dev $NPM_MIRROR_PARAM $NPM_CACHE_PARAM
#   echo "start install node_modules1"
#   # npm run install-deps $NPM_MIRROR_PARAM $NPM_CACHE_PARAM
#   npm install $NPM_MIRROR_PARAM $NPM_CACHE_PARAM
# }

SQLITE_BINARY_PARAM="--node_sqlite3_binary_host_mirror=https://npmmirror.com/mirrors/sqlite3 "

install_node_modules_by_npm() {
  echo "use npm to install node_modules"
  npm install $NPM_MIRROR_PARAM $NPM_CACHE_PARAM $SQLITE_BINARY_PARAM
}

remove_and_install_node_modules() {
  if [ -d "$CURRENT_APP_PATH" ]; then
    echo "remove node_modules"
    rm -rf ./node_modules
  fi
  install_node_modules_by_npm
}

echo "npm cache: $NPM_CACHE_PARAM"
install_node_modules_by_npm

exit_code=$?
echo "exit_code: $exit_code"

echo "lmdprogress:80"

if [ $exit_code -ne 0 ]; then
  remove_and_install_node_modules
fi
exit_code=$?

echo "lmdprogress:82"

echo "exit_code: $exit_code"
if [ $exit_code -ne 0 ]; then   
  install_node_modules_by_npm
fi
exit_code=$?

echo "lmdprogress:85"

if [ $exit_code -ne 0 ]; then
  echo "exit_code: "$exit_code
  exit 1
fi

echo "lmdprogress:100"
